﻿using System;
using System.Collections.Generic;
using System.Text;
using ExpressionUtil.Node.Common;
using ExpressionUtil.Parser;
using ExpressionUtil.Exceptions;

namespace ExpressionUtil.Common
{
    /// <summary>
    /// 检查助手类（主要处理解析和执行时的检查）
    /// </summary>
    internal static class CheckHelper
    {
        /// <summary>
        /// 检查创建处理程序是否存在
        /// </summary>
        /// <param name="op">运算符或函数标识符</param>
        /// <param name="msg">检查的错误信息</param>
        public static void CreateHandlerExists(string op, string msg)
        {
            if (!ParseContext.CreateHandlerMap.ContainsKey(op))
            {
                throw new FormatException(msg);
            }
        }

        /// <summary>
        /// 检查类型是否为数字类型
        /// </summary>
        /// <param name="type">类型枚举</param>
        /// <param name="msg">检查的错误信息</param>
        public static void IsDecimalType(ExecuteRunTimeType type, string msg)
        {
            if (type != ExecuteRunTimeType.Decimal)
            {
                throw new RunTimeTypeErrorException(msg);
            }
        }

        /// <summary>
        /// 检查类型是否为布尔类型
        /// </summary>
        /// <param name="type">类型枚举</param>
        /// <param name="msg">检查的错误信息</param>
        public static void IsBoolType(ExecuteRunTimeType type, string msg)
        {
            if (type != ExecuteRunTimeType.Bool)
            {
                throw new RunTimeTypeErrorException(msg);
            }
        }

        /// <summary>
        /// 检查两个类型是否相同
        /// </summary>
        /// <param name="type1">类型枚举1</param>
        /// <param name="type2">类型枚举2</param>
        /// <param name="msg">检查的错误信息</param>
        public static void AreSameType(ExecuteRunTimeType type1, ExecuteRunTimeType type2, string msg)
        {
            if (type1 != type2)
            {
                throw new RunTimeTypeErrorException(msg);
            }
        }

        /// <summary>
        /// 检查数字类型变量是否存在
        /// </summary>
        /// <param name="dic">变量集合</param>
        /// <param name="name">变量名称</param>
        public static void DecimalValueExists(Dictionary<string, decimal> dic, string name)
        {
            if (!dic.ContainsKey(name))
            {
                throw new RunTimeTypeErrorException("Variable value must be setted before execute,variable name:" + name);
            }
        }

        /// <summary>
        /// 检查布尔类型变量是否存在
        /// </summary>
        /// <param name="dic">变量集合</param>
        /// <param name="name">变量名称</param>
        public static void BoolValueExists(Dictionary<string, bool> dic, string name)
        {
            if (!dic.ContainsKey(name))
            {
                throw new RunTimeTypeErrorException("Variable value must be setted before execute,variable name:" + name);
            }
        }
    }
}
